package edu.usc.epigenome.dnaase.script;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import net.sf.samtools.BAMFileWriter;
import net.sf.samtools.SAMFileHeader;
import net.sf.samtools.SAMFileReader;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.util.CloseableIterator;

import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

import edu.usc.epigenome.genomeLibs.PicardUtils;

public class getSamInPositionWanted {

	final private static String USAGE = "getSamInPositionWanted [opts] snpFileName bamFile outputBamFile...";

	final private static int PURGE_INTERVAL = 20000;
	
//	@Option(name="-minMapQ",usage="minimum mapping quality (default 0)")
//	protected int minMapQ = 0;
//	@Option(name="-minBaseQual",usage="minimum Base quality (default 0)")
//	protected int minBaseQual = 0;
	@Option(name="-baseBefore",usage="get some base Before position (default 5)")
	protected int baseBefore = 5;
	@Option(name="-baseAfter",usage="get some base After position (default 5)")
	protected int baseAfter = 5;
	
	
	@Argument
	private List<String> stringArgs = new ArrayList<String>();
	
	public static void main(String[] args)
	throws Exception
	{
		getSamInPositionWanted test = new getSamInPositionWanted();
		test.doMain(args);
	}

	public void doMain(String[] args)
	throws Exception {

		CmdLineParser parser = new CmdLineParser(this);
		// if you have a wider console, you could increase the value;
		// here 80 is also the default
		parser.setUsageWidth(80);
		try
		{
			parser.parseArgument(args);
			if (stringArgs.size() < 3) throw new CmdLineException(USAGE);
		
		}
		catch (CmdLineException e)
		{
			System.err.println(e.getMessage());
			// print the list of available options
			parser.printUsage(System.err);
			System.err.println();
			return;
		}

		
		String snpFileName = stringArgs.remove(0);
		String bamFileName = stringArgs.remove(0);
		String outputBamFile = stringArgs.remove(0);
		BufferedReader br = new BufferedReader(new FileReader(snpFileName));
		String line;
		
		File inputSamOrBamFile = new File(bamFileName);
		File outputBam = new File(outputBamFile);
		SAMFileReader inputSam = new SAMFileReader(inputSamOrBamFile);
		inputSam.setValidationStringency(SAMFileReader.ValidationStringency.SILENT);
		SAMFileHeader samHeader = inputSam.getFileHeader();
		BAMFileWriter writer = new BAMFileWriter(outputBam);
		writer.setHeader(samHeader);
		int recCounter = 1;
		while( (line = br.readLine()) != null){
			String[] tmpArray = line.split("\t");
			String chr = "chr" + tmpArray[1];
			
			
			Integer snpPosition =(int) Math.round(Double.parseDouble(tmpArray[2]));
			
			Integer start = snpPosition - baseBefore;
			
			Integer end = snpPosition - baseAfter;
			
			CloseableIterator<SAMRecord> chrIt = inputSam.queryOverlapping(chr, start, end);
			record: while (chrIt.hasNext())
			{	
				SAMRecord samRecord = chrIt.next();
			//	int mapQual = samRecord.getMappingQuality();
			//	byte[] baseQual = samRecord.getBaseQualities();
			//	boolean unmapped = samRecord.getReadUnmappedFlag();
			//	if (unmapped || (mapQual <= minMapQ))
			//	{
			//		continue record;
			//	}
				writer.addAlignment(samRecord);
				
					
				
				
			}
			chrIt.close();	
			if ((recCounter % 1000)==0)
			{
				System.err.printf("On new record #%d\n",recCounter);
				inputSam.close();
				
				System.gc();
				inputSam = new SAMFileReader(inputSamOrBamFile);
				inputSam.setValidationStringency(SAMFileReader.ValidationStringency.SILENT);
				
			}
		}
		inputSam.close();
		writer.close();
	}

}
